package org.example.execute;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.maven.plugin.logging.Log;
import org.example.dto.ColumnDto;
import org.example.service.GenerateCode;
import org.example.utils.HumpUtils;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

public class ServiceImpl implements GenerateCode {
    public static void execute(Log log, String classPath, String entity, Properties properties) {
        String className = HumpUtils.className(StrUtil.format("{}_service_impl", entity));
        String extendsClassName = HumpUtils.className(StrUtil.format("{}_service", entity));
        try {
            String path = StrUtil.format("src/main/java/{}/{}.java", classPath.replaceAll("\\.", "/"), className);
            FileUtil.file(path.substring(0, path.lastIndexOf("/"))).mkdirs();
            FileUtil.file(path).createNewFile();
            log.info(FileUtil.file(path).getPath());
            FileWriter writer = new FileWriter(path);
            writer.write(StrUtil.format("package {};\n\n", classPath));
            writer.write(StrUtil.format("import {}.{};\n", properties.getProperty("generator.service.path"), extendsClassName));
            writer.write(StrUtil.format("import org.springframework.stereotype.Service;\n\n"));
            writer.write("@Service\n");
            writer.write(String.format(StrUtil.format("public class {} implements {} %s", className, extendsClassName), "{\n\n}"));
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void execute(Log log, String entity, List<ColumnDto> columnDtoList, Properties properties) {
        Boolean serviceImpl = Boolean.parseBoolean(properties.getProperty("generator.service_impl"));
        if (serviceImpl) {
            String path = properties.getProperty("generator.service_impl.path");
            log.info(path);
            log.info(entity + "service_impl 生成");
            ServiceImpl.execute(log, path, entity, properties);
        }
    }
}
